package com.webull.information.center.carwler.task;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.webull.information.center.carwler.common.model.NewsInformation;
import com.webull.information.center.carwler.common.model.hs.MfNews;
import com.webull.information.center.carwler.common.model.hs.parm.PageParm;
import com.webull.information.center.carwler.dao.HangsengNewsDao;
import com.webull.information.center.carwler.task.support.TikcerNewsProcessor;
import com.webull.information.center.common.constants.Constants;
import com.webull.information.client.model.News;
import com.webull.information.client.model.parm.NewsRelType;
import com.webull.securities.client.model.Fund;
import com.webull.securities.client.model.parm.FundParam;
import com.webull.securities.client.service.FundService;

@Component
public class News_HengShengCnFund_Task {
	protected final Logger logger = LogManager.getLogger(getClass());

	private @Autowired HangsengNewsDao hangsengNewsDao;
	// private @Autowired @Qualifier("executor") ThreadPoolTaskExecutor
	// threadPoolTaskExecutor;
	private final Integer pageSize = 100;
	private @Autowired FundService fundService;
	private @Autowired TikcerNewsProcessor tikcerNewsProcessor;

	/**
	 * 基金动态新闻
	 * 
	 * @param start
	 * @param end
	 * @since 0.1.0
	 */
	public void hengShengFundCrawlerTask(final Date start, final Date end) {

		logger.info("HengShengCrawlerNewsTask.hengShengFundCrawler2Task start start:{},end:{} ", start, end);
		int pageNo = 0;
		full: do {
			PageParm pageParm = new PageParm();
			pageParm.setStartDate(start);
			pageParm.setEndDate(end);
			pageParm.setPageNo(pageNo++);
			pageParm.setPageSize(pageSize);
			List<MfNews> res = hangsengNewsDao.pageFundMfNews(pageParm);
			if (res == null || res.isEmpty()) {
				break full;
			}
			logger.info("HengShengCrawlerNewsTask.hengShengFundCrawler2Task stocks:" + res.size());
			procss(res);
		} while (true);
		/**
		 * 研究报告
		 */
		hengShengFundCrawler2Task(DateUtils.addDays(start, -30), end);// 查询的报告范围
	}

	/**
	 * 基金研究报告
	 * 
	 * @param start
	 * @param end
	 * @since 0.1.0
	 */
	private void hengShengFundCrawler2Task(final Date start, final Date end) {
		logger.info("HengShengCrawlerNewsTask.hengShengFundCrawler2Task start start:{},end:{} ", start, end);
		int pageNo = 0;
		full: do {
			PageParm pageParm = new PageParm();
			pageParm.setStartDate(start);
			pageParm.setEndDate(end);
			pageParm.setPageNo(pageNo++);
			pageParm.setPageSize(pageSize);
			List<MfNews> res = hangsengNewsDao.pageFundAnalyReport(pageParm);
			if (res == null || res.isEmpty()) {
				break full;
			}
			logger.info("HengShengCrawlerNewsTask.hengShengFundCrawler2Task stocks:" + res.size());
			procss(res);
		} while (true);

	}

	private void procss(List<MfNews> res) {
		try {
			if (res == null)
				return;
			for (MfNews s : res) {
				// MfNews s2 = new MfNews();
				// BeanUtils.copyProperties(s, s2);
				try {
					newsProcess.accept(s);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error(e);
				}
			}
			logger.info("HengShengCrawlerNewsTaskTask procss end::::" + res.size());
		} catch (Exception e) {
			logger.error("HengShengCrawlerNewsTaskTask 全量新闻任务失败", e);
		}
	}

	Consumer<MfNews> newsProcess = new Consumer<MfNews>() {

		@Override
		public void accept(MfNews t) {
			if (StringUtils.isBlank(t.getSecuCode()))
				return;
			// 查找fund
			FundParam param = new FundParam();
			param.setSymbol(t.getSecuCode());
			param.setRegionId(1);// 中国大陆
			Fund fund = Optional.ofNullable(fundService.paging(param))
					.map(page0 -> !page0.isEmpty() ? page0.get(0) : null).orElse(null);
			if (fund == null)
				return;
			Integer tickerId = fund.getTickerId();

			// 转information
			NewsInformation info = coverInfomation(t);
			// add news
			tikcerNewsProcessor.bindTargetNewsRecord(info, tickerId, NewsRelType.ticker);
		}

		private NewsInformation coverInfomation(MfNews t) {
			if (t == null)
				return null;
			NewsInformation info = new NewsInformation();
			info.setLanguage(Constants.lang_zh);
			info.setRegionId(1);// 中国大陆

			info.setCollectSource(News.CollectSource.hengSheng);

			info.setUrl(News.CollectSource.hengSheng + "_" + t.getID());
			info.setUrlMd5(DigestUtils.sha1Hex(info.getUrl()));

			info.setNewsTime(t.getInfoPublDate());
			info.setSourceName(t.getMedia());
			info.setTitle(t.getInfoTitle());
			info.setContent(t.getContent());
			return info;
		}
	};

}
